package day27;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class WorkServer2 {
    public static void main(String[] args) {
        try (ServerSocket server = new ServerSocket(9999)) {
            while (true) {
                Socket client = server.accept();
                System.out.println(client.getInetAddress() + "连接成功");
                handleClient(client);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleClient(Socket client) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
            while (true) {
                String s1 = br.readLine();
                if (s1 == null || s1.isEmpty()) break;
                String[] s = s1.split(" ");
                String str = s[0];
                double num1 = Double.parseDouble(s[1]);
                double num2 = Double.parseDouble(s[2]);
                double result = 0;
                String resultStr = "";
                switch (str) {
                    case "add":
                        result = num1 + num2;
                        break;
                    case "minus":
                        result = num1 - num2;
                        break;
                    case "multiply":
                        result = num1 * num2;
                        break;
                    case "divide":
                        if (num2 != 0) {
                            result = num1 / num2;
                        } else {
                            resultStr = "除数不能为零";
                        }
                        break;
                    default:
                        resultStr = "无效操作";
                }
                if (resultStr.isEmpty()) {
                    resultStr = Double.toString(result);
                }
                bw.write(resultStr + "\n");
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
